package main

import (
	"context"
	"feng-che.com/server/driver-quiz/internal/pay"
	"feng-che.com/server/driver-quiz/internal/user"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// InsertDBIndexs 在数据库中创建索引，需要在启动的最后步骤运行
func InsertDBIndexs() {
	_indexUser()
	_indexPayment()
}

func _indexUser() {
	indexView := (&user.User{}).GetCollection().Indexes()
	models := []mongo.IndexModel{
		{
			Keys: bson.D{
				{"person.auth_info.login_name", 1},
			},
			Options: options.Index().SetUnique(true),
		},
		{
			Keys: bson.D{
				{"person.information.name", 1},
			},
		},
		{
			Keys: bson.D{
				{"person.contact.phone", 1},
			},
			Options: options.Index().SetUnique(true),
		},
	}
	opts := options.CreateIndexes()
	_, err := indexView.CreateMany(context.TODO(), models, opts)
	if err != nil {
		fmt.Println("create gate db index error," + err.Error())
	}
}

func _indexPayment() {
	indexView := (&pay.Payment{}).GetCollection().Indexes()
	models := []mongo.IndexModel{
		{
			Keys: bson.D{
				{"payer_info.id", 1},
			},
		},
		{
			Keys: bson.D{
				{"payer_info.open_id", 1},
			},
		},
		{
			Keys: bson.D{
				{"state", 1},
			},
			Options: options.Index().SetUnique(true),
		},
	}
	opts := options.CreateIndexes()
	_, err := indexView.CreateMany(context.TODO(), models, opts)
	if err != nil {
		fmt.Println("create gate db index error," + err.Error())
	}
}
